<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { message } from 'ant-design-vue';

interface Product {
  id: string;
  name: string;
  specification: string;
  unit: string;
  unitPrice: number;
  quantity: number;
  addedBy: string;
  category: string;
}

interface Props {
  visible: boolean;
  dose?: any;
}

interface Emits {
  (e: 'update:visible',visible: boolean): void;
  (e: 'success',products: Product[]): void
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const searchKeyword = ref('');
const selectedCategory = ref('');
const selectedProducts = ref<Product[]>([]);
const selectedRowKeys = ref<string[]>([]);
const selectionMode = ref<'multiple' | 'single'>('multiple');

// 模拟商品数据
const products = ref<Product[]>([
  {
    id: '1',
    name: '宠必威@幼犬保(4联)',
    specification: '1支',
    unit: '支',
    unitPrice: 120,
    quantity: 1,
    addedBy: '孙医生',
    category: 'vaccine',
  },
  {
    id: '2',
    name: '瑞倍尔安狂犬疫苗',
    specification: '1支',
    unit: '支',
    unitPrice: 80,
    quantity: 1,
    addedBy: '孙医生',
    category: 'vaccine',
  },
  {
    id: '3',
    name: '美国辉瑞狂犬',
    specification: '1支',
    unit: '支',
    unitPrice: 150,
    quantity: 1,
    addedBy: '孙医生',
    category: 'vaccine',
  },
  {
    id: '4',
    name: '英特威狂犬疫苗',
    specification: '1支',
    unit: '支',
    unitPrice: 100,
    quantity: 1,
    addedBy: '孙医生',
    category: 'vaccine',
  },
  {
    id: '5',
    name: '英特威猫三联',
    specification: '1支',
    unit: '支',
    unitPrice: 90,
    quantity: 1,
    addedBy: '孙医生',
    category: 'vaccine',
  },
  {
    id: '6',
    name: '拜耳驱虫药',
    specification: '1片',
    unit: '片',
    unitPrice: 25,
    quantity: 1,
    addedBy: '孙医生',
    category: 'deworming',
  },
  {
    id: '7',
    name: '福来恩驱虫滴剂',
    specification: '1支',
    unit: '支',
    unitPrice: 45,
    quantity: 1,
    addedBy: '孙医生',
    category: 'deworming',
  },
]);

// 商品选择相关方法
const toggleProductSelection = (product: Product) => {
  const index = selectedRowKeys.value.indexOf(product.id);
  if (index === -1) {
    // 添加商品
    selectedRowKeys.value.push(product.id);
    selectedProducts.value.push({
      id: product.id,
      name: product.name,
      specification: product.specification,
      unit: product.unit,
      unitPrice: product.unitPrice,
      category: product.category,
      quantity: 1,
      addedBy: '孙医生',
    });
  } else {
    // 移除商品
    selectedRowKeys.value.splice(index, 1);
    const productIndex = selectedProducts.value.findIndex(
      (p) => p.id === product.id,
    );
    if (productIndex !== -1) {
      selectedProducts.value.splice(productIndex, 1);
    }
  }
};

const handleProductCheckboxChange = (product: Product, checked: boolean) => {
  if (checked) {
    // 添加商品
    if (!selectedRowKeys.value.includes(product.id)) {
      selectedRowKeys.value.push(product.id);
      selectedProducts.value.push({
        id: product.id,
        name: product.name,
        specification: product.specification,
        unit: product.unit,
        unitPrice: product.unitPrice,
        category: product.category,
        quantity: 1,
        addedBy: '孙医生',
      });
    }
  } else {
    // 移除商品
    const index = selectedRowKeys.value.indexOf(product.id);
    if (index !== -1) {
      selectedRowKeys.value.splice(index, 1);
      const productIndex = selectedProducts.value.findIndex(
        (p) => p.id === product.id,
      );
      if (productIndex !== -1) {
        selectedProducts.value.splice(productIndex, 1);
      }
    }
  }
};

// 计算属性
const filteredProducts = computed(() => {
  let filtered = products.value;

  // 按分类筛选
  if (selectedCategory.value) {
    filtered = filtered.filter(
      (product) => product.category === selectedCategory.value,
    );
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    filtered = filtered.filter(
      (product) =>
        product.name
          .toLowerCase()
          .includes(searchKeyword.value.toLowerCase()) ||
        product.id.includes(searchKeyword.value),
    );
  }

  return filtered;
});

const selectedTotal = computed(() => {
  return selectedProducts.value.reduce((total, product) => {
    return total + product.unitPrice * product.quantity;
  }, 0);
});

// 移除 rowSelection，使用新的 Grid 选择方式

// 方法
const handleSearch = () => {
  // 搜索逻辑已在计算属性中实现
};

const clearAllSelected = () => {
  selectedProducts.value = [];
  selectedRowKeys.value = [];
  message.success('已清空所有选择的商品');
};

const removeSelectedProduct = (product: Product) => {
  const index = selectedProducts.value.findIndex((p) => p.id === product.id);
  if (index !== -1) {
    selectedProducts.value.splice(index, 1);
    // 从选中行中移除
    const keyIndex = selectedRowKeys.value.indexOf(product.id);
    if (keyIndex !== -1) {
      selectedRowKeys.value.splice(keyIndex, 1);
    }
  }
};

const handleCancel = () => {
  emit('update:visible', false);
  // 重置状态
  selectedProducts.value = [];
  selectedRowKeys.value = [];
  searchKeyword.value = '';
  selectedCategory.value = '';
};

const handleConfirm = () => {
  if (selectedProducts.value.length === 0) {
    message.warning('请至少选择一个商品');
    return;
  }

  emit('success', selectedProducts.value);
  handleCancel();
};

// 监听模态框显示状态
watch(
  () => props.visible,
  (visible) => {
    if (!visible) {
      // 重置状态
      selectedProducts.value = [];
      selectedRowKeys.value = [];
      searchKeyword.value = '';
      selectedCategory.value = '';
    }
  },
);
</script>

<template>
  <a-modal
    :visible="visible"
    title="选择商品"
    width="1000px"
    @cancel="handleCancel"
    :footer="null"
  >
    <div class="product-modal">
      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <a-input-search
          :value="searchKeyword"
          placeholder="搜索商品名称/编码/条形码"
          @search="handleSearch"
          @update:value="searchKeyword = $event"
          style="width: 300px"
        />
        <a-select
          :value="selectedCategory"
          style="width: 150px; margin-left: 16px"
          placeholder="选择分类"
          @update:value="selectedCategory = $event"
        >
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="vaccine">疫苗服务</a-select-option>
          <a-select-option value="deworming">驱虫服务</a-select-option>
        </a-select>
        <a-radio-group
          :value="selectionMode"
          @update:value="selectionMode = $event"
          style="margin-left: 16px"
        >
          <a-radio-button value="single">单选</a-radio-button>
          <a-radio-button value="multiple">多选</a-radio-button>
        </a-radio-group>
      </div>

      <!-- 商品列表和已选商品 -->
      <div class="content-section">
        <!-- 商品列表 -->
        <div class="products-list">
          <h4>商品列表</h4>
          <div class="product-grid">
            <div
              v-for="product in filteredProducts"
              :key="product.id"
              class="product-card"
              :class="{ selected: selectedRowKeys.includes(product.id) }"
              @click="toggleProductSelection(product)"
            >
              <div class="product-checkbox">
                <a-checkbox
                  :checked="selectedRowKeys.includes(product.id)"
                  @change="
                    (e) =>
                      handleProductCheckboxChange(product, e.target.checked)
                  "
                />
              </div>
              <div class="product-info">
                <div class="product-name">{{ product.name }}</div>
                <div class="product-spec">{{ product.specification }}</div>
                <div class="product-price">
                  ¥{{ product.unitPrice.toFixed(2) }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 已选商品 -->
        <div class="selected-products">
          <div class="selected-header">
            <h4>已选择的商品 ({{ selectedProducts.length }})</h4>
            <a-button type="text" size="small" @click="clearAllSelected">
              清空全部
            </a-button>
          </div>
          <div class="selected-list">
            <div
              v-for="product in selectedProducts"
              :key="product.id"
              class="selected-item"
            >
              <div class="item-info">
                <div class="item-name">{{ product.name }}</div>
                <div class="item-spec">{{ product.specification }}</div>
              </div>
              <div class="item-controls">
                <a-input-number
                  :value="product.quantity"
                  :min="1"
                  :max="999"
                  size="small"
                  style="width: 80px"
                  @update:value="product.quantity = $event"
                />
                <a-button
                  type="text"
                  size="small"
                  danger
                  @click="removeSelectedProduct(product)"
                >
                  删除
                </a-button>
              </div>
            </div>
          </div>
          <div class="total-section">
            <span class="total-label">合计：</span>
            <span class="total-amount">¥{{ selectedTotal.toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="modal-actions">
        <a-button @click="handleCancel">取消</a-button>
        <a-button
          type="primary"
          @click="handleConfirm"
          :disabled="selectedProducts.length === 0"
        >
          确认添加
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

<style scoped>
.product-modal {
  display: flex;
  flex-direction: column;
  height: 600px;
}

.search-section {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  margin-bottom: 16px;
}

.content-section {
  display: flex;
  flex: 1;
  gap: 16px;
  overflow: hidden;
}

.products-list {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
  max-height: 300px;
  padding: 8px;
  overflow-y: auto;
}

.product-card {
  display: flex;
  align-items: center;
  padding: 12px;
  cursor: pointer;
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  transition: all 0.3s;
}

.product-card:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgb(24 144 255 / 10%);
}

.product-card.selected {
  background: #e6f7ff;
  border-color: #1890ff;
}

.product-checkbox {
  flex-shrink: 0;
  margin-right: 12px;
}

.product-info {
  flex: 1;
  min-width: 0;
}

.product-name {
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 14px;
  font-weight: bold;
  color: #333;
  white-space: nowrap;
}

.product-spec {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.product-price {
  font-size: 14px;
  font-weight: bold;
  color: #1890ff;
}

.products-list h4 {
  margin-bottom: 12px;
  color: #333;
}

.selected-products {
  display: flex;
  flex-shrink: 0;
  flex-direction: column;
  width: 350px;
  padding-left: 16px;
  border-left: 1px solid #e8e8e8;
}

.selected-header {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.selected-header h4 {
  margin: 0;
  color: #333;
}

.selected-list {
  flex: 1;
  max-height: 300px;
  overflow-y: auto;
}

.selected-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px;
  margin-bottom: 8px;
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.item-info {
  flex: 1;
}

.item-name {
  margin-bottom: 4px;
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.item-spec {
  font-size: 12px;
  color: #666;
}

.item-controls {
  display: flex;
  gap: 8px;
  align-items: center;
}

.total-section {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: space-between;
  padding-top: 12px;
  margin-top: 12px;
  border-top: 1px solid #e8e8e8;
}

.total-label {
  font-size: 14px;
  color: #333;
}

.total-amount {
  font-size: 16px;
  font-weight: bold;
  color: #1890ff;
}

.modal-actions {
  display: flex;
  flex-shrink: 0;
  gap: 8px;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>
